package com.xjrsoft.module.workflow.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xjrsoft.core.tool.utils.*;
import com.xjrsoft.module.base.entity.XjrBaseTempfield;
import com.xjrsoft.module.base.service.IXjrBaseTempfieldService;
import com.xjrsoft.module.workflow.entity.XjrNwfScheme;
import com.xjrsoft.module.workflow.entity.XjrNwfSchemeinfo;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeInfoService;
import com.xjrsoft.module.workflow.service.IXjrNwfSchemeService;
import lombok.SneakyThrows;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityImpl;
import org.flowable.engine.repository.ProcessDefinition;

import java.util.Date;
import java.util.Optional;


//流程创建监听
public class StartExecutionListener implements ExecutionListener {

    @SneakyThrows
    @Override
    public void notify(DelegateExecution delegateExecution) {
        IXjrBaseTempfieldService xjrBaseTempfieldService = SpringUtil.getBean(IXjrBaseTempfieldService.class);
        IXjrNwfSchemeInfoService nwfSchemeInfoService = SpringUtil.getBean(IXjrNwfSchemeInfoService.class);
        IXjrNwfSchemeService nwfSchemeService = SpringUtil.getBean(IXjrNwfSchemeService.class);
        RepositoryService repositoryService = SpringUtil.getBean(RepositoryService.class);
        RuntimeService runtimeService = SpringUtil.getBean(RuntimeService.class);
        ExecutionEntityImpl execution = (ExecutionEntityImpl) delegateExecution;
        ExecutionEntityImpl superExecution = execution.getSuperExecution();
        if (superExecution != null) {
            // 设置当前操作人，对于调用活动可以获取到当前操作人
            Object username = runtimeService.getVariable(delegateExecution.getSuperExecutionId(), "username");
            if (username != null) {
                ((ExecutionEntityImpl) delegateExecution).setVariable("initiator", String.valueOf(username));
                Object initiator = delegateExecution.getVariable("initiator");
                System.out.println(initiator);
            }
        }
        Integer serialNumber = FlowableUtil.setSerialNumber();
        XjrBaseTempfield xjrBaseTempfield = new XjrBaseTempfield();
        xjrBaseTempfield.setType("19");
        xjrBaseTempfield.setFkey(delegateExecution.getProcessInstanceId());
        xjrBaseTempfield.setFvalue(String.valueOf(serialNumber));
        xjrBaseTempfield.setCreateTime(new Date());
        xjrBaseTempfieldService.save(xjrBaseTempfield);
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(delegateExecution.getProcessDefinitionId()).singleResult();
        String nwfSchemeInfoId = processDefinition.getDescription();
        XjrNwfSchemeinfo xjrNwfSchemeinfo = nwfSchemeInfoService.getById(nwfSchemeInfoId);
        if (xjrNwfSchemeinfo != null) {
            XjrNwfScheme xjrNwfScheme = nwfSchemeService.getBySchemeInfoId(xjrNwfSchemeinfo.getId());
            // 获取会签节点的获选人
            JSONObject formValues = new JSONObject();
            String fjson = xjrNwfScheme.getFjson();
            JSONArray childShapes = (JSONObject.parseObject(fjson)).getJSONArray("childShapes");
            Optional<Object> startNode = childShapes.stream().filter(s -> "StartNoneEvent".equals(((JSONObject) s).getJSONObject("stencil").getString("id"))).findFirst();
//            if (startNode.isPresent()) {
//                Object node = startNode.get();
//                String currentResourceId = ((JSONObject) node).getString("resourceId");
//                JSONArray nextMultiinstanceResourceId = JsonUtil.getNextMultiinstanceResourceId(childShapes, currentResourceId);
//                for (int i = 0; i < nextMultiinstanceResourceId.size(); i++) {
//                    XjrBaseTempfield xjrBaseTempfield1 = xjrBaseTempfieldService.getByIdAndType(xjrNwfScheme.getSchemeInfoId() + StringPool.UNDERSCORE + nextMultiinstanceResourceId.getString(i) + StringPool.UNDERSCORE + String.valueOf(processDefinition.getVersion()), "1");
//                    if (xjrBaseTempfield1 != null) {
//                        String resourceId = nextMultiinstanceResourceId.getString(i);
//                        JSONArray userArray = new JSONArray();
//                        userArray.add("xxx");
//                        formValues.put(resourceId + StringPool.UNDERSCORE + "usernamelist", userArray);
//                    }
//                }
//            }
            try {
                formValues.putAll(FlowableUtil.setParamVariable(null, processDefinition.getId(), xjrNwfScheme, null, delegateExecution.getProcessInstanceId()));
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            //保存流程变量
            runtimeService.setVariables(delegateExecution.getProcessInstanceId(), formValues);
            //开始节点的表单信息
            if (((ExecutionEntity) delegateExecution).getSuperExecution() != null) {
                JSONArray startForms = new JSONArray();
                for (int i = 0; i < childShapes.size(); i++) {
                    JSONObject childShape = childShapes.getJSONObject(i);
                    String startActivityId = ((ExecutionEntity) delegateExecution).getStartActivityId();
                    String resourceId = childShape.getString("resourceId");
                    if (StringUtil.equals(resourceId, startActivityId)) {
                        JSONArray tableDatas = childShape.getJSONObject("properties").getJSONArray("tableData");
                        for (Object tableData : tableDatas) {
                            JSONObject tableDataObj = (JSONObject) tableData;
                            JSONObject startFormObj = new JSONObject();
                            String f_url = tableDataObj.getString("F_Url");
                            if (StringUtil.isNotBlank(f_url)) {
                                String[] split = f_url.split(StringPool.SLASH);
                                f_url = split[split.length - 1];
                            }
                            startFormObj.put("F_UrlAddress", f_url);
                            startFormObj.put("F_Id", "");
                            startFormObj.put("F_Type", tableDataObj.getString("F_Type"));
                            startFormObj.put("F_FormId", tableDataObj.getString("F_Id"));
                            startForms.add(startFormObj);
                        }
                        break;
                    }
                }
                runtimeService.updateBusinessKey(delegateExecution.getProcessInstanceId(), JSON.toJSONString(startForms));
                //保存开始节点绑定的表单信息
                XjrBaseTempfield startFormInfo = new XjrBaseTempfield();
                startFormInfo.setType("25");
                startFormInfo.setFvalue(JSON.toJSONString(startForms));
                startFormInfo.setFkey(delegateExecution.getProcessInstanceId() + StringPool.UNDERSCORE + ((ExecutionEntity) delegateExecution).getStartActivityId());
                xjrBaseTempfieldService.save(startFormInfo);
            }
        }
        // 2.自定义任务命名
        FlowableUtil.taskNameRule(delegateExecution.getProcessDefinitionId(), delegateExecution.getProcessInstanceId());
    }
}
